package handler

import (
	"context"
	"errors"
	"gitee.com/wendyRose/common"
	paymentapi "gitee.com/wendyRose/payment-api/proto/payment-api"
	"gitee.com/wendyRose/payment/proto/payment"
	"github.com/plutov/paypal/v3"
	"strconv"
)

type PaymentApi struct{
	PaymentService payment.PaymentService
}

var(
	ClientID string = ""
)

// PaymentApi.Call is called by the API as /payment-api/payPalRefund with post body {"name": "foo"}
func (e *PaymentApi) PayPalRefund(ctx context.Context, request *paymentapi.Request, response *paymentapi.Response) error {
	common.Info("Received PaymentApi.payPalRefund request")

	if _, ok := request.Get["payment_id"]; !ok{
		response.StatusCode = 500
		err := errors.New("payment_id 参数异常")
		common.Error(err)
		return err
	}

	if _, ok := request.Get["refund_id"]; !ok {
		response.StatusCode = 500
		err := errors.New("refund_id 参数异常")
		common.Error(err)
		return err
	}

	if _, ok := request.Get["money"]; !ok {
		response.StatusCode = 500
		err := errors.New("money 参数异常")
		common.Error(err)
		return err
	}

	payID, err := strconv.ParseInt(request.Get["payment_id"].Values[0], 10, 64)
	if err != nil {
		common.Error(err)
		return err
	}

	paymentInfo, err := e.PaymentService.FindPaymentByID(ctx, &payment.PaymentID{PaymentId: payID})
	if err != nil {
		common.Error(err)
		return err
	}
	status := paypal.APIBaseSandBox
	if paymentInfo.PaymentStatus {
		status = paypal.APIBaseLive
	}
	payout := paypal.Payout{
		SenderBatchHeader: &paypal.SenderBatchHeader{
			EmailSubject:  request.Get["refund_id"].Values[0] + "xxxx",
			EmailMessage:  request.Get["refund_id"].Values[0] + "xxxx",
			SenderBatchID: request.Get["refund_id"].Values[0],
		},
		Items:             []paypal.PayoutItem{
			{
				RecipientType: "EMAIL",
				//RecipientWallet: "",
				Receiver: "aaa",
				Amount: &paypal.AmountPayout{
					Currency: "USD",
					Value:    request.Get["money"].Values[0],
				},
				Note: request.Get["refund_id"].Values[0],
				SenderItemID: request.Get["refund_id"].Values[0],
			},
		},
	}

	payPalClient, err := paypal.NewClient(ClientID, paymentInfo.PaymentSid, status)
	if err != nil {
		common.Error(err)
	}
	_, err = payPalClient.GetAccessToken()
	if err != nil {
		common.Error(err)
	}
	paymentResult, err := payPalClient.CreateSinglePayout(payout)
	if err != nil {
		common.Error(err)
	}
	common.Info(paymentResult)
	response.Body = request.Get["refund_id"].Values[0] + "支付成功"
	return err
}
